<?php

namespace App\Jobs\Activity;

use App\Models\Activity\ActivityModel;
use App\Models\Activity\ShopOrderActivityModel;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;

class HandleActivityFinishStatusJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $id;


    /**
     * 允许误差时间（秒）
     */
    const ALLOW_EXPIRED_TIME = 10;


    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(int $id)
    {
        $this->id = $id;
    }


    /**
     * Execute the job.
     *
     * @return void
     * @throws Exception
     */
    public function handle()
    {
        logInfo(
            vsprintf("%s 消杀活动延时过期执行 %s", [
                Carbon::now()->format("Y-m-d H:i:s"),
                $this->id
            ]),
            collect(["id" => $this->id])
        );

        try {
            $model = ActivityModel::query()->where("id", $this->id)->first();
            if ($model && $model->expireType == ActivityModel::EXPIRE_TYPE_1) {
                $residueTime = $model->endTime - time();
                if ($residueTime <= self::ALLOW_EXPIRED_TIME) {
                    $model->update([
                        "status"    => ActivityModel::STATUS_3,
                        "updatedAt" => time()
                    ]);
                }
            }
        } catch (Exception $exception) {
            logException("消杀活动延时过期报错 {$this->id}", $exception, ["id" => $this->id]);
        }
    }
}
